import { sleep, sleepTime } from '@/utils/index';
import IpcParams from "../IpcParams";
import { createAgent } from './utils';
import Axios from 'axios';
import axiosRetry from 'axios-retry';

export default class PiggyGame {
  constructor(gameInfo) {
    this.gameInfo = gameInfo
    const agent = createAgent(this.gameInfo.proxy)
    const headers = {
      "Referer": "https://restaurant-v2.piggypiggy.io",
      "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_7_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
      "content-type": "application/json",
      "sec-fetch-site": "same-site",
      "accept-language": "zh-CN,zh-Hans;q=0.9",
      "accept-encoding": "gzip, deflate, br",
      "sec-fetch-mode": "cors",
      "sec-fetch-dest": "empty",
    }
    this.axios = Axios.create({
      headers: headers,
      httpAgent: agent,
      httpsAgent: agent,
    })
    axiosRetry(this.axios, {
      retries: 3, retryDelay: (retryCount) => {
        return 2000
      }
    });
  }

  async run() {
    try {
      console.log(Date().toLocaleString(), "piggy begin", this.gameInfo.phone)
      const axios = this.axios
      let webSessionUrl = this.gameInfo.tgweb
      if (webSessionUrl.startsWith("https://") == false) {
        console.error(`${this.gameInfo.phone}  error session url ${webSessionUrl}`);
        return
      }
      webSessionUrl = decodeURIComponent(webSessionUrl)
      let session = webSessionUrl.split("#tgWebAppData=")[1]
      session = session.split("&tgWebAppVersion")[0]
      const inviteUrl = this.gameInfo.inviteUrl
      let refId = "6162453001";
      if (inviteUrl != null) {
        refId = inviteUrl.split("share_")[1]
      }
      const res = await axios.request("https://api.prod.piggypiggy.io/tgBot/login?" + session + `&invite_id=${refId}`)
      const token = res.data.data.token
      const authHeader = {
        authorization: "bearer " + token
      }
      this.authHeader = authHeader
      await this.refreshPlayerBase()
      await this.dailyBox()
      await this.sign7DayTask()
      await this.signDailyRewards()
      await this.startPlunder()
      await this.startMayo()
      // 天使宝藏
      await this.angleRewards()
      await this.achievementRewards()

      // 开始工作
      const signUp = await this.axios.request("https://api.prod.piggypiggy.io/game/SetUpShop", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
        }
      })

      // 自动任务
      const taskList = [
        {
          "taskID": 1001,
          "compeleteCount": 2,
          "lastCompleteTime": 1725372232832
        },
        {
          "taskID": 1002,
          "compeleteCount": 5,
          "lastCompleteTime": 1725372343347
        },
        {
          "taskID": 1003,
          "compeleteCount": 8,
          "lastCompleteTime": 1725375223488
        },
        {
          "taskID": 1004,
          "compeleteCount": 8,
          "lastCompleteTime": 1725375400956
        },
        {
          "taskID": 1005,
          "compeleteCount": 5,
          "lastCompleteTime": 1725375731965
        },
        {
          "taskID": 1006,
          "compeleteCount": 5,
          "lastCompleteTime": 1725375842709
        }
      ]
      for (let index = 0; index < taskList.length; index++) {
        const task = taskList[index];
        const compeleteCount = task.compeleteCount
        for (let compIndex = 0; compIndex < compeleteCount; compIndex++) {
          console.log("begin task", task.taskID, compIndex)
          const takeTask = await this.axios.request("https://api.prod.piggypiggy.io/game/TakeTask", {
            method: "post",
            headers: authHeader,
            data: {
              TaskId: task.taskID,
              PlayerID: 0,
              AD: 1,
            }
          })
          if (takeTask.data.code != 0) {
            break
          }
          await sleepTime(Math.random() * 1)
          const compTask = await this.axios.request("https://api.prod.piggypiggy.io/game/CompleteTask", {
            method: "post",
            headers: authHeader,
            data: {
              TaskId: task.taskID,
              PlayerID: 0,
              AD: 1,
            }
          })
          console.log("complete", compTask.data)
          await sleepTime(Math.random() * 5 + 20)
        }
      }
      await this.refreshPlayerBase()
      this.gameInfo.score = this.playerBase.currency
      this.gameInfo.gameupdate = (new Date()).toLocaleString()
      this.gameInfo.count = (this.gameInfo.count || 0) + 1
      console.log(Date().toLocaleString(), "piggy end", this.gameInfo.phone, "score: ", this.gameInfo.score)
      return new IpcParams("runPiggy", this.gameInfo)
    } catch (error) {
      console.error(Date().toLocaleString(), "piggy error", this.gameInfo.phone)
      console.error(error)
      return new IpcParams("runPiggy", this.gameInfo, error)
    }
  }

  async refreshPlayerBase() {
    try {
      await this.axios.request("https://api.prod.piggypiggy.io/game/GetAchievementInfo", {
        method: "post",
        headers: this.authHeader,
      })
      await this.axios.request("https://api.prod.piggypiggy.io/game/PlunderRecord", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
          Page: 1,
          PageSize: 1,
        }
      })
      await this.axios.request("https://api.prod.piggypiggy.io/game/GetBountryList", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
        }
      })

      const userBaseRes = await this.axios.request("https://api.prod.piggypiggy.io/game/GetPlayerBase", {
        method: "post",
        headers: this.authHeader,
      })
      this.playerBase = userBaseRes.data.data
    } catch (error) {
      console.error(error)
    }
  }

  async sign7DayTask() {
    try {
      const day7 = await this.axios.request("https://api.prod.piggypiggy.io/game/Get7DayInfo", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
        }
      })
      const sign7Day = await this.axios.request("https://api.prod.piggypiggy.io/game/Sign7Day", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
          Type: 0,
        }
      })
    } catch (error) {
      console.error(error)
    }
  }

  async signDailyRewards() {
    try {
      const daily = await this.axios.request("https://api.prod.piggypiggy.io/game/CarnivalTaskTake", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
          TaskID: 1001,
        }
      })
    } catch (error) {
      console.error(error)
    }
  }

  async angleRewards() {
    try {
      const refreshRes = await this.axios.request("https://api.prod.piggypiggy.io/game/angel_box_flush", {
        method: "post",
        headers: this.authHeader,
        data: {
          "PlayerID": 0
        }
      })
      const angleInfoRes = await this.axios.request("https://api.prod.piggypiggy.io/game/angel_box_info", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
        }
      })
      const box = angleInfoRes.data.data.box
      if (box == null) {
        return
      }
      const angleTask = box.tasks
      for (let index = 0; index < angleTask.length; index++) {
        const element = angleTask[index];
        const finishAngle = await this.axios.request("https://api.prod.piggypiggy.io/game/angel_task_finish", {
          method: "post",
          headers: this.authHeader,
          data: {
            Id: element.taskID,
            PlayerID: 0,
          }
        })
        console.log("piggy angel task finish", finishAngle.data.data)
        await sleep(Math.random() * 2000 + 15)
      }
      const angleClaimRes = await this.axios.request("https://api.prod.piggypiggy.io/game/angel_box_claim", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
        }
      })
      console.log("piggy angel task claimed", angleClaimRes.data)
    } catch (error) {
      console.error(error)
    }
  }

  async achievementRewards() {
    try {
      const achRes = await this.axios.request("https://api.prod.piggypiggy.io/game/GetAchievementInfo", {
        method: "post",
        headers: this.authHeader,
      })
      const achTaskMap = achRes.data.data.mapInfo
      for (const key in achTaskMap) {
        if (Object.prototype.hasOwnProperty.call(achTaskMap, key)) {
          const task = achTaskMap[key];
          const schedule = task.schedule
          const addScheduleRes = await this.axios.request("https://api.prod.piggypiggy.io/game/AddSchedule", {
            method: "post",
            headers: this.authHeader,
            data: {
              Type: 2,
              Id: parseInt(key),
              PlayerID: 0,
            }
          })
          await sleep(schedule * 2100)
          const compRes = await this.axios.request("https://api.prod.piggypiggy.io/game/CompleteAchievement", {
            method: "post",
            headers: this.authHeader,
            data: {
              AchievementID: parseInt(key),
              PlayerID: 0,
            }
          })
          console.log("piggy CompleteAchievement", compRes.data.data)
          await sleep(1000)
        }
      }
    } catch (error) {
      console.error(error)
    }
  }

  async startPlunder() {
    try {
      const detailRes = await this.axios.request("https://api.prod.piggypiggy.io/game/PlunderDetail", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
        }
      })
      const playerId = this.playerBase.playerID
      const startRes = await this.axios.request("https://api.prod.piggypiggy.io/game/StartAPlunder", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: playerId,
        }
      })
      const startData = startRes.data
      if (startData.code == 20002) {
        return
      }
      const takeRes = await this.axios.request("https://api.prod.piggypiggy.io/game/TakeAPlunder", {
        method: "post",
        headers: this.authHeader,
        data: {
          "PlayerID": 0,
          "Pos": 2,
        }
      })
      console.log("takePlunder", takeRes.data.data)
    } catch (error) {
      console.error(error)
    }
  }

  async startMayo() {
    try {
      const res = await this.axios.request("https://api.prod.piggypiggy.io/game/StartMoyu", {
        method: "post",
        headers: this.authHeader,
        data: {
          PlayerID: 0,
        }
      })
      console.log("StartMoyu", res.data.data)
    } catch (error) {
      console.error(error)
    }
  }

  // 每日宝箱
  async dailyBox() {
    try {
      const res = await this.axios.request("https://api.prod.piggypiggy.io/game/CreateStarPay", {
        method: 'post',
        headers: this.authHeader,
        data: {
          "RoleType": 0,
          "PlayerID": 0,
          "UseStar": 0,
          "ConfigID": "2001",
          "Param": "",
          "ClientParam": "2001",
          "Count": 1
        }
      })
      console.log("每日宝箱", res.data)
    } catch (error) {
      console.error(error)
    }
  }
}